<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
    <% String path=request.getContextPath(); String basePath=request.getScheme() + "://" + request.getServerName() + ":"
        + request.getServerPort() + path + "/" ; %>

        <!DOCTYPE html>
        <html>

        <head>
            <base href="<%=basePath%>">

            <title>变更生效</title>

            <meta http-equiv="pragma" content="no-cache">
            <meta http-equiv="cache-control" content="no-cache">
            <meta http-equiv="expires" content="0">
            <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
            <meta http-equiv="description" content="This is my page">
            <!--
            <link rel="stylesheet" type="text/css" href="styles.css">
            -->
            <style>
                .tdText {
                    text-align: right;
                    width: 400px;
                    height: 20px;
                }

                input:disabled {
                    background-color: #dae1ed;
                }
            </style>
        </head>

        <body>
            <%@ include file="/WEB-INF/jsp/common/header.jsp" %>
                <%@ include file="/WEB-INF/jsp/common/loadDiv.jsp" %>

                    <script type="text/javascript">
                        $(function () {
                            $('#startOrderTime').datebox('setValue', getBeforeCurrentDate90Days());
                            $('#endOrderTime').datebox('setValue', getNowFormatDate());
                            $('#startTime').datebox('setValue', getBeforeCurrentDate90Days());
                            $('#endTime').datebox('setValue', getNowFormatDate());
                            // 初始化合同签署列表
                            bindgrid();
                            // 初始化采购订单查询列表
                            setOrdersDataGrid();
                            $("#uploadbtn").bind("click", function (e) {
                                $("#uploadpicker").click();
                            });
                        });

                        // 获取当前日期前30天并格式化
                        function getBeforeCurrentDateDays_t(months) {
                            let day_30 = new Date().setMonth((new Date().getMonth() - months));    //日期是30天前的对应时间戳
                            day_30 = new Date(day_30);       //转换成标准时间
                            let y = day_30.getFullYear();    //年
                            let m = day_30.getMonth() + 1;    //月
                            let d = day_30.getDate();         //日
                            if (m < 10) {
                                m = '0' + m;
                            }
                            if (d < 10) {
                                d = '0' + d;
                            }
                            day_30 = y + '-' + m + '-' + d;
                            return day_30;
                        }
                    </script>
                    <script>

                    </script>

                    <style scoped="scoped">
                        .textbox {
                            height: 20px;
                            margin: 0;
                            padding: 0 2px;
                            box-sizing: content-box;
                        }

                        /*.table tr {
                height: 15px;
            }*/
                    </style>

                    <div class="query_criteria" id="query_criteria">
                        <div style="margin: 5px 0px">
                            <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox" name="startTime"
                                id="startTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                class="easyui-datebox" name="endTime" id="endTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                style="width: 150px" /> <label style="margin-left: 20px; font-size: 12px;">状态：</label>
                            <input class="easyui-combobox" id="status" name="status" style="width: 80px;" data-options="valueField: 'value',editable:false,
		textField: 'label',panelHeight:'auto',data: [{
			label: '全部',
			value: ''
		},{
			label: '待提交',
			value: '0',
			'selected':true
		},{
			label: '已提交',
			value: '1'
		}]">
                            <a id="search" href="javascript:void(0)" class="easyui-linkbutton"
                                data-options="iconCls:'icon-search'" onclick="searchContractList()">查询</a>
                            <%-- <a id="export" href="javascript:void(0)" class="easyui-linkbutton"
                                data-options="iconCls:'icon-export'" onclick="exportInquiryResul()">导出</a>--%>
                        </div>
                        <table id="dg"></table>
                        <div id="add" class="easyui-window" closed="true" modal="true" title="合同签署"
                            style="width: 900px; height: 400px; padding: 5px 5px">
                            <form id="fm">
                                <div class="easyui-tabs" id="tabs" style="width: 875px; height: 350px">
                                    <div title="基本信息" style="padding: 5px;">
                                        <table>
                                            <tr>
                                                <td>
                                                    <!-- 签署id-->
                                                    <input id="ctrId" type="hidden" name="ctrId" />
                                                    <!-- 合同起草id-->
                                                    <input id="ordId" type="hidden" name="ordId" />
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">询价名称：</div>
                                                </td>

                                                <td>
                                                    <div class="ssec-text normal" onclick="searchOrders()">
                                                        <input id="resName" name="resName" class="easyui-textbox"
                                                            data-options="prompt:'点此选择采购订单'" />
                                                    </div>

                                                </td>
                                                <td>
                                                    <div class="ssec-label">订单编号：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="ordCode" name="ordCode" class="easyui-textbox"
                                                            data-options="disabled:true" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">相关说明：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="ordDetail" name="ordDetail" class="easyui-textbox"
                                                            data-options="disabled:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td>
                                                    <div class="ssec-label">创建时间：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createTime" name="createTime" class="easyui-textbox"
                                                            data-options="disabled:true" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">创建人：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="createName" name="createName" class="easyui-textbox"
                                                            data-options="disabled:true" />
                                                    </div>
                                                </td>
                                                <td>
                                                    <div class="ssec-label">备注：</div>
                                                </td>
                                                <td>
                                                    <div class="ssec-text normal">
                                                        <input id="remark" name="remark" class="easyui-textbox"
                                                            data-options="disabled:false" />
                                                    </div>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                    <div title="附件" style="padding: 5px;">
                                        <table>
                                            <tr>
                                                <td colspan="3"><input type="button" id="uploadbtn" value="选择文件..." />
                                                    <input type="file" id="uploadpicker" accept=""
                                                        onchange="changeFile()" multiple style="display: none;" />
                                                    <span>（文件名称不能包含斜杠、空格、&、#等特殊字符）</span>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td><label style="width: 40%; text-align: right;">附件下载：</label>
                                                    <ul id="checkfileList"></ul>
                                                </td>
                                            </tr>
                                        </table>
                                    </div>
                                </div>
                            </form>
                        </div>

                        <div id="order" class="easyui-window" closed="true" modal="true" title="采购订单"
                            style="width: 900px; height: 400px; padding: 5px 5px">
                            <label style="font-size: 12px;">创建时间：</label> <input class="easyui-datebox"
                                id="startOrderTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                value="" style="width: 150px"> <label style="font-size: 10px;">~</label> <input
                                class="easyui-datebox" id="endOrderTime"
                                data-options="required:true,showSeconds:false,formatter:myformatter,parser:myparser"
                                style="width: 150px" /> <a style="margin-left: 30px" href="javascript:void(0)"
                                class="easyui-linkbutton" data-options="iconCls:'icon-search'"
                                onclick="selectOrderList()">查询</a><a style="margin-left: 5px" href="javascript:void(0)"
                                class="easyui-linkbutton" data-options="iconCls:'icon-ok'"
                                onclick="saveOrderToContract()">确定</a>
                            <!--采购订单列表DataGrid  -->
                            <table id="orderList"></table>
                        </div>
                    </div>
        </body>
        <script>
            var selectedFileList = [];//已选文件列表
            var succsessCount = 0;//上传成功文件个数
            var errorCount = 0;//上传失败文件个数
            /**
             * 保存选中的订单至合同
             */
            function saveOrderToContract() {
                let row = $('#orderList').datagrid('getSelected')
                if (!row) {
                    $.messager.alert('提示', '请选择一个采购订单')
                    return
                }
                $('#ctrId').val('')
                $('#ordId').val(row.ordId)
                $('#resName').textbox('setValue', row.resName)
                $('#ordCode').textbox('setValue', row.ordCode)
                $('#ordDetail').textbox('setValue', row.ordDetail)
                $('#ordDetail').textbox('setValue', row.ordDetail)

                $('#order').window('close')
            }

            function saveContract(action) {
                let contract = {
                    ctrId: $('#ctrId').val(),
                    ordId: $('#ordId').val(),
                    resName: $('#resName').textbox('getValue'),
                    ordCode: $('#ordCode').textbox('getValue'),
                    ordDetail: $('#ordDetail').textbox('getValue'),
                    remark: $('#remark').textbox('getValue'),
                    status: '0'
                }
                save(contract, action)
            }

            function save(obj, action) {
                $.ajax({
                    type: 'post',
                    url: 'purchase/contract/change/save',
                    data: JSON.stringify(obj),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code == 60200) {
                            const result = data.data
                            // 保存附件
                            saveAttch(result.ctrId, obj, action)
                            if ('save' == action) {
                                $.messager.alert('消息', data.msg)
                                let dg = $('#dg');
                                dg.datagrid('enableFilter');
                                dg.datagrid('load');
                                $('#add').window('close');
                            }

                        } else {
                            $.messager.alert('消息', data.msg)
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })

            }

            /**
             * 采购订单查询方法
             */
            function selectOrderList() {
                let startTime = $('#startOrderTime').datebox('getValue')
                let endTime = $('#endOrderTime').datebox('getValue')
                let dg = $('#orderList')
                dg.datagrid('enableFilter')
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: '1'
                })
            }

            /**
             * 新增采购订单
             */
            function addOrder() {
                $('#tabs').tabs({
                    tools: [{
                        text: '保存',
                        iconCls: 'icon-save',
                        handler: function () {
                            saveContract('save')
                        }
                    }, {
                        text: '提交',
                        iconCls: 'icon-ok',
                        handler: function () {
                            $.messager.confirm('提示', '提交后无法再次编辑，确定要提交吗?',
                                function (r) {
                                    if (r) {
                                        saveContract('submit');
                                    }
                                });
                        }
                    }]
                })

                // 新增时可以弹出选择框
                $('#order').window({
                    onBeforeOpen: function () {
                        return true
                    }
                })
                $('#add').window('open');
                $('#tabs').tabs('select', 0);
            }

            function searchOrders() {
                $('#order').window('open');
                $('#tabs').tabs('select', 0);
                selectOrderList();
            }

            // 设置采购订单的dataGrid
            function setOrdersDataGrid() {
                let startTime = $('#startOrderTime').datebox('getValue');
                let endTime = $('#endOrderTime').datebox('getValue');
                let dg = $('#orderList');
                dg.datagrid({
                    queryParams: {
                        startTime: startTime ? startTime : '',
                        endTime: endTime ? endTime : '',
                        status: '1'
                    },
                    url: 'purchase/order/change/selectList',
                    iconCls: 'icon-application',
                    clientPaging: false,
                    remoteFilter: true,
                    filterDelay: 0,
                    width: 860,
                    height: 310,
                    nowrap: true,
                    rownumbers: true,
                    animate: false,
                    collapsible: false,
                    singleSelect: true,
                    pageSize: 10,
                    remoteSort: true,
                    pagination: true,
                    frozenColumns: [[{
                        field: 'ck',
                        checkbox: true,
                        width: 100,
                        formatter: function (val, rec) {
                            return unescape(val ? val : '')
                        }
                    }, {
                        field: 'resId',
                        title: '询价结果id',
                        hidden: true,
                        width: 100,
                        formatter: function (val, rec) {
                            return unescape(val)
                        }
                    },
                    {
                        field: 'ordId',
                        title: '订单Id',
                        hidden: true,
                        width: 100,
                        formatter: function (val, rec) {
                            return unescape(val)
                        }
                    },
                    {
                        field: 'ordCode',
                        title: '订单编号',
                        sortable: true,
                        formatter: function (val, rec, index) {
                            return val ? val : ''
                        }
                    },
                    {
                        field: 'ordName',
                        title: '订单名称',
                        sortable: true,
                        formatter: function (val, rec, index) {
                            return val ? val : ''
                        }
                    },]],
                    columns: [
                        [
                            {
                                field: 'resCode',
                                title: '询价结果编码',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return val ? val : ''
                                }
                            },
                            {
                                field: 'resName',
                                title: '结果名称',
                                sortable: true,
                                formatter: function (val, rec, index) {

                                    return val ? val : ''

                                }
                            }, {
                                field: 'infCode',
                                title: '供应商编码',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'infName',
                                title: '供应商名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordContractType',
                                title: '合同类别',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordFreight',
                                title: '运费',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordIncidental',
                                title: '杂费',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordSignAddress',
                                title: '签订地点',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordSignDate',
                                title: '签订日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordResultDate',
                                title: '生效日期',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'ordIsSign',
                                title: '是否签订合同文本',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createName',
                                title: '创建人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            },
                            {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return unescape(val ? val : '')
                                }
                            }
                        ]
                    ],
                    toolbar: [
                        //     {
                        //     text: '确定',
                        //     iconCls: 'icon-ok',
                        //     handler: function () {
                        //         // setTabToolBar('add')
                        //         saveOrderToContract()
                        //     }
                        // },
                        /*
                    '-',
                    {
                        text: '关闭',
                        iconCls: 'icon-cancel',
                        handler: function () {
                            $('#add').window('close')
                        }
                    }*/
                    ],
                    onLoadSuccess: function () {

                    },
                    onDblClickRow: function () {

                    }
                });

                dg.datagrid('enableFilter');

            }
            function submitContract(obj) {
                if ($('#checkfileList li').length == 0) {
                    $.messager.confirm("提示", "附件为空，确定提交?", function (e) {
                        if (e) {
                            submitAjax(obj);
                        } else {
                            return;
                        }
                    })
                } else {
                    submitAjax(obj);
                }
            }

            function submitAjax(obj) {
                obj.status = '1'
                $('#add').window('close')
                $.ajax({
                    type: 'post',
                    url: 'purchase/contract/change/commit',
                    data: JSON.stringify(obj),
                    dataType: 'json',
                    contentType: "application/json",
                    success: function (data) {
                        if (data.code == 60200) {
                            $.messager.alert('消息', data.msg)
                            setOrdersDataGrid();
                            let dg = $('#dg');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        } else {
                            $.messager.alert('消息', data.msg)
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                })
            }

            /**
             * 提交合同
             */
            function commitContract(index) {
                const rows = $('#dg').datagrid('getRows')
                let row = rows[index]
                if (!row) return
                if (+row.status == '1') {
                    $.messager.alert('消息', '该合同已提交，无需再次提交')
                    return
                }
                $.messager.confirm('提示', '确定要提交吗?',
                    function (r) {
                        if (r) {
                            save(row, 'submit')
                        }
                    });

            }

            function del(node) {
                $.ajax({
                    type: "delete",
                    url: 'purchase/contract/change/delete?id=' + node.ctrId,
                    //                dataType: "xml",
                    success: function (data) {
                        if (data.code == 60200) {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#dg');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        } else {
                            $.messager.alert('消息', data.msg);
                        }

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                });
            }

            function back(node) {
                $.ajax({
                    type: "get",
                    url: 'purchase/contract/change/back?id=' + node.ctrId,
                    //                dataType: "xml",
                    success: function (data) {
                        if (data.code == 60200) {
                            $.messager.alert('消息', data.msg);
                            let dg = $('#dg');
                            dg.datagrid('enableFilter');
                            dg.datagrid('load');
                        } else {
                            $.messager.alert('消息', data.msg);
                        }

                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                });
            }

            function getRowByIndewx(index) {
                const rows = $('#dg').datagrid('getRows')
                let row = rows[index]
                setContractDetail(row)
            }

            /**
             * 编辑
             * */
            function editRow(row) {
                if ('1' == row.status) {
                    $.messager.alert('提示', '该合同已提交，不可再次编辑')
                    return
                }

                setContractDetail(row)

            }

            /**
             * 设置合同签署详情
             */
            function setContractDetail(row) {
                // 编辑时不得弹出选择框
                $('#order').window({
                    onBeforeOpen: function () {
                        return false
                    }
                })
                $('#ctrId').val(row.ctrId)
                $('#ordId').val(row.ordId)
                $('#resName').textbox('setValue', row.resName)
                $('#ordCode').textbox('setValue', row.ordCode)
                $('#ordDetail').textbox('setValue', row.ordDetail)
                $('#createTime').textbox('setValue', row.createTime)
                $('#createName').textbox('setValue', row.createName)
                $('#remark').textbox('setValue', row.remark)
                // 取得附件列表
                getFileList(row)
                if ('1' != row.status) {
                    $('#tabs').tabs({
                        tools: [{
                            text: '保存',
                            iconCls: 'icon-save',
                            handler: function () {
                                saveContract('save')
                            }
                        }, {
                            text: '提交',
                            iconCls: 'icon-ok',
                            handler: function () {
                                $.messager.confirm('提示', '提交后无法再次编辑，确定要提交吗?',
                                    function (r) {
                                        if (r) {
                                            saveContract('submit');
                                        }
                                    });
                            }
                        }]
                    })
                } else {
                    $('#tabs').tabs({
                        tools: []
                    })
                }
                $('#add').window('open')
                $('#tabs').tabs('select', 0);
            }

            function bindgrid() {
                let startTime = $('#startTime').datebox('getValue')
                let endTime = $('#endTime').datebox('getValue')
                let status = $('#status').combobox('getValue')
                $('#dg').datagrid(
                    {
                        title: '',
                        queryParams: {
                            startTime: startTime ? startTime : '',
                            endTime: endTime ? endTime : '',
                            status: status
                        },
                        url: "purchase/contract/change/selectList",
                        iconCls: 'icon-application',
                        width: getWidth(0.98),
                        height: 400,
                        nowrap: true,
                        rownumbers: true,
                        animate: false,
                        collapsible: false,
                        clientPaging: false,
                        remoteFilter: true,
                        singleSelect: true,
                        filterDelay: 0,
                        pagination: true,
                        remoteSort: true,
                        frozenColumns: [[{
                            field: 'ctrId',
                            title: '订单id',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'ordId',
                            title: '订单id',
                            sortable: true,
                            hidden: true,
                            formatter: function (val, rec) {
                                return val ? unescape(val) : '';
                            }
                        }, {
                            field: 'ordCode',
                            title: '订单编号',
                            sortable: true,
                            formatter: function (val, rec, index) {
                                return '<a href="javascript:void(0)" onclick="getRowByIndewx(' + index +
                                    ')">' + (val ? val : '') + '</a>'
                            }
                        },]],
                        columns: [
                            [{
                                field: 'resName',
                                title: '订单名称',
                                sortable: true,
                                formatter: function (val, rec, index) {
                                    return val ? val : ''
                                }
                            }, {
                                field: 'deptName',
                                title: '供应商名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'ordContractName',
                                title: '供应商联系人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'ordDetail',
                                title: '相关说明',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'createName',
                                title: '创建人',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'createTime',
                                title: '创建时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'createId',
                                title: 'create_id',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'updateId',
                                title: 'update_id',
                                sortable: true,
                                hidden: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'updateName',
                                title: '更新人名称',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'updateTime',
                                title: '更新时间',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, {
                                field: 'status',
                                title: '状态',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape((val == '1' ? '已提交' : '待提交')) : '';
                                }
                            }, {
                                field: 'remark',
                                title: '备注',
                                sortable: true,
                                formatter: function (val, rec) {
                                    return val ? unescape(val) : '';
                                }
                            }, /*{
                        field: 'action',
                        title: '操作',
                        formatter: function (val, rec, index) {
                            if (+rec.status == '1') {
                                return '<a style="text-decoration:none" href="javascript:void(0)">' + '--' + '</a>'
                            } else {
                                return '<a style="text-decoration:none" href="javascript:void(0)" onclick="commitContract(' + index + ')">' + '提交' + '</a>'

                            }

                        }
                    }*/]],
                        toolbar: [
                            {
                                text: '新增',
                                iconCls: 'icon-add',
                                handler: function () {
                                    $('#fm').form('clear');
                                    selectedFileList = []
                                    $("#checkfileList").empty();
                                    var obj = document.getElementById('uploadpicker');
                                    obj.outerHTML = obj.outerHTML;
                                    addOrder()
                                }
                            },
                            '-',
                            {
                                text: '编辑',
                                iconCls: 'icon-edit',
                                handler: function () {
                                    var obj = document.getElementById('uploadpicker');
                                    obj.outerHTML = obj.outerHTML;
                                    var row = $('#dg').datagrid(
                                        'getSelected');
                                    if (row) {
                                        editRow(row)
                                    } else {
                                        $.messager.alert('提示', '请选择要编辑的数据')
                                        return
                                    }
                                }
                            }, '-',
                            {
                                text: '删除',
                                iconCls: 'icon-cancel',
                                handler: function () {
                                    var row = $('#dg').datagrid(
                                        'getSelected');
                                    if (+row.status == '1') {
                                        $.messager.alert('消息', '已提交，无法删除!');
                                        return
                                    }
                                    if (row) {
                                        $.messager.confirm('提示',
                                            '确定要删除吗?', function (r) {
                                                if (r) {
                                                    del(row);
                                                }
                                            });
                                    }
                                }
                            }
                            // , '-',
                            // {
                            //     text: '撤回',
                            //     iconCls: 'icon-undo',
                            //     handler: function () {
                            //         var row = $('#dg').datagrid(
                            //             'getSelected');
                            //         if (+row.status == '0') {
                            //             $.messager.alert('消息', '未提交，无法撤回!');
                            //             return
                            //         }
                            //         if (row) {
                            //             $.messager.confirm('提示',
                            //                 '撤回只可修改附件，确定要撤回吗?', function (r) {
                            //                     if (r) {
                            //                         back(row);
                            //                     }
                            //                 });
                            //         }
                            //     }
                            // }
                        ],
                        onLoadSuccess: function () {
                        },
                        onDblClickRow: function () {
                            var obj = document.getElementById('uploadpicker');
                            obj.outerHTML = obj.outerHTML;
                            var row = $('#dg').datagrid(
                                'getSelected');
                            if (row) {
                                editRow(row)
                            } else {
                                $.messager.alert('提示', '请选择要编辑的数据')
                                return
                            }
                        }

                    }
                )
                    ;
                $('#dg').datagrid('enableFilter');
            }

            /**
             *  条件查询合同签署列表
             */
            function searchContractList() {
                let startTime = $('#startTime').datebox('getValue')
                let endTime = $('#endTime').datebox('getValue')
                let status = $('#status').combobox('getValue')
                let dg = $('#dg');
                dg.datagrid('enableFilter');
                dg.datagrid('load', {
                    startTime: startTime ? startTime : '',
                    endTime: endTime ? endTime : '',
                    status: status
                })
            }

            /************文件处理部分*************/

            /**
             * 保存附件
             */

            function saveAttch(row, obj, action) {
                obj.ctrId = row
                let saveNum = 0
                if (selectedFileList.length > 0) {
                    $.each(selectedFileList, function (index, item) {
                        showFilediv();
                        var dataform = new FormData();
                        dataform.append("file", item);
                        var xmlhttp = null;
                        if (window.XMLHttpRequest) { // code for all new browsers
                            xmlhttp = new XMLHttpRequest();
                        } else if (window.ActiveXObject) {// code for IE5 and IE6
                            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                        }
                        if (xmlhttp != null) {
                            xmlhttp.open("POST", "api/file/springUpload?fileRow=" + row
                                + "&fileTable=purchase_contract_change&fileName="
                                + item.name, true);
                            xmlhttp.setRequestHeader('token', localStorage.getItem('token'));
                            xmlhttp.setRequestHeader('userType', localStorage.getItem('userType'));
                            xmlhttp.send(dataform);
                            xmlhttp.onreadystatechange = callbackMethods;
                        } else {
                            alert("你的浏览器版本不兼容，请使用更高版本的浏览器");
                        }

                        function callbackMethods() {
                            if (xmlhttp.readyState == 4) {
                                if (xmlhttp.status == 200) {
                                    saveNum += 1
                                }
                                if (saveNum == selectedFileList.length) {
                                    hideFilediv();
                                    if ('submit' == action) {
                                        submitContract(obj)
                                    }
                                }
                            } else {
                                if (xmlhttp.status == 500) {
                                }
                            }
                        }
                    });
                } else {
                    if ('submit' == action) {
                        submitContract(obj)
                    }
                }
            }

            /**
             *文件框改变事件
             */
            function changeFile() {
                var files = $("#uploadpicker").prop("files");
                $.each(
                    files,
                    function (index, item) {
                        let choiseFile = $("#checkfileList>li");
                        if (choiseFile.length > 0) {//文件去重
                            let count = 0;
                            $.each(choiseFile, function (index1, item1) {
                                if (item.name == item1.innerText) {
                                    count++;
                                }
                            });
                            if (count == 0) {
                                if (checkFileLength(item.size)) {
                                    if (item.name.includes('#') || item.name.includes('/') || item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                        alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                        return;
                                    }
                                    $("#checkfileList")
                                        .append(
                                            "<li class=\"fileinfo\">"
                                            + item.name
                                            + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                            + item.name
                                            + "')\">删除</a>"
                                            + "</li>");
                                    selectedFileList.push(item);
                                    AddMoushover();
                                }
                            }
                        } else {
                            if (checkFileLength(item.size)) {
                                if (item.name.includes('#') || item.name.includes('/') || item.name.includes('&') || item.name.includes('\\') || item.name.includes(' ')) {
                                    alert('文件名不能包含&、斜杠、反斜杠、空格等特殊字符！');
                                    return;
                                }
                                $("#checkfileList")
                                    .append(
                                        "<li class=\"fileinfo\">"
                                        + item.name
                                        + "<a style=\"display: none; color: red; margin-left: 10px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                        + item.name
                                        + "')\">删除</a>"
                                        + "</li>");
                                selectedFileList.push(item);
                                // 										sselectedFileNameList.push(item.name);
                                AddMoushover();
                            }
                        }
                    });
            }

            /**
             *    判断文件是否超过限制大小
             * @param fileLen
             * @returns {boolean}
             */
            function checkFileLength(fileLen) {
                if (fileLen > 102400000) {
                    $.messager.alert("提示", "上传文件大小不能超过100M", "error");
                    return false;
                }
                return true;
            }

            /**
             * //添加鼠标经过事件，鼠标划过时显示“删除”
             * @constructor
             */
            function AddMoushover() {
                $(".fileinfo").hover(function () {
                    $(this).find("a").last().css("display", "");
                }, function () {
                    $(this).find("a").last().css("display", "none");
                });
            }

            /**
             *  移除已选择的文件
             */

            function RemoveFile(obj, fileId) {

                $.messager.confirm("提示", "确认删除当前文件?", function (e) {
                    if (e) {
                        let index = $("#checkfileList>li").index($(obj).parent());
                        selectedFileList.splice(index, 1);
                        $(obj).parent().remove();
                        // 					var index1 = $.inArray(filename, sselectedFileNameList);
                        // 					sselectedFileNameList.splice(index1, 1);
                        $.ajax({
                            type: "post",
                            url: 'file/deleteFile?fileId=' + fileId,
                            success: function (data) {
                                $.messager.alert('消息', data);
                            },
                            error: function (XMLHttpRequest, textStatus,
                                errorThrown) {
                                $.messager.alert('消息', errorThrown);
                            }
                        });

                    }
                });
            }

            /**
             * 取得该条数据所属的文件列表
             * @param row
             */
            function getFileList(row, status) {
                $.ajax({
                    type: "post",
                    url: "file/getFileList",
                    data: {
                        fileTable: "purchase_contract_change",
                        fileRow: row.ctrId
                    },
                    success: function (data) {
                        const dataArray = eval(data);
                        initFile(dataArray, row.status);
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.messager.alert('消息', errorThrown);
                    }
                });
            }

            /**
             * 初始化该条数据的文件列表
             * @param dataArray
             */
            function initFile(dataArray, status) {
                $("#checkfileList").empty();
                // 			sselectedFileNameList = [];
                selectedFileList = [];
                dataArray
                    .forEach(function (e, i, a) {
                        $("#checkfileList")
                            .append(
                                "<li class=\"fileinfo\">"
                                + "<a style=\" color: blue; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"downloadFile('" + e.FILE_NAME + "','"
                                + e.FILE_ID
                                + "')\">"
                                + e.FILE_NAME
                                + (status > 0 ? '' : "<a style=\"display: none; color: red; margin-left: 30px;\" href=\"javascript:void(0)\" onclick=\"RemoveFile(this,'"
                                    + e.FILE_ID + "')\">删除</a>")
                                + "</li>");

                        if (status > 0) {
                        } else {
                            AddMoushover();
                        }

                    });
            }

            function downloadFile(fileName, fileRow) {
                console.log('file>>>', fileRow)
                let url = 'api/file/download?id=' + fileRow
                let xhr = new XMLHttpRequest()
                xhr.open('GET', url, true)
                xhr.setRequestHeader('token', localStorage.getItem('token'));
                xhr.setRequestHeader('userType', localStorage.getItem('userType'));
                xhr.responseType = 'blob'
                xhr.onload = function (data) {
                    console.log('data,,,,' + data)
                    if (this.status == 200) {
                        let blob = this.response
                        let reader = new FileReader()
                        reader.readAsDataURL(blob)
                        reader.onload = function (e) {
                            let a = document.createElement('a')
                            a.download = fileName
                            a.href = e.target.result
                            $('body').append(a)
                            a.click()
                            $(a).remove()
                        }
                    } else {

                    }
                }
                xhr.send()
            }
        </script>

        </html>